
package com.supplychainapi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.FinderList;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.common.exception.ExceptionManager;
import com.supplychainapi.dao.prod.ScmTbmaterialMapper;
import com.supplychainapi.dao.prod.ScmTbtempletMapper;
import com.supplychainapi.dao.prod.ScmTbtempletdtlMapper;
import com.supplychainapi.domain.templet.*;
import com.supplychainapi.model.ScmTbmaterial;
import com.supplychainapi.model.ScmTbseqno;
import com.supplychainapi.model.ScmTbtemplet;
import com.supplychainapi.model.ScmTbtempletdtl;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.service.TbSeqNoService;
import com.supplychainapi.service.TbTempletService;
import com.supplychainapi.utils.Constants;
import com.supplychainapi.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TbTempletServiceImpl implements TbTempletService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ScmTbtempletMapper scmTbtempletMapper;

    @Autowired
    private ScmTbtempletdtlMapper scmTbtempletdtlMapper;

    @Autowired
    private TbSeqNoService tbSeqNoService;

    @Autowired
    private ScmTbmaterialMapper scmTbmaterialMapper;

    @Override
    public List getSchema() {
        List<ColTitle> list = new ArrayList<ColTitle>();
        list.add(new ColTitle("fsTempletName", "清单名称", "left", 200));
        list.add(new ColTitle("fsApplyName", "使用单位", "left", 100));
        list.add(new ColTitle("fsUpdateTime", "修改日期", "center", 100));
        list.add(new ColTitle("fiStatusName", "状态", "center", 100));
        list.add(new ColTitle("__EDIT__", "操作", "center", 100, "fsTempletId"));
        return list;
    }

    @Override
    public RestResponse getList(TempletListSearch templetListSearch) {

        PageHelper.startPage(templetListSearch.getPageNum(), templetListSearch.getPageSize());

        // 查询常用清单列表
        List<ScmTbtemplet> list = scmTbtempletMapper.getList(templetListSearch);

        List<TempletListResponse> templetListResponselist = new ArrayList<TempletListResponse>();

        list.forEach((ScmTbtemplet scmTbtemplet) -> {
            TempletListResponse templetListResponse = new TempletListResponse();
            BeanUtils.copyProperties(scmTbtemplet, templetListResponse);
            templetListResponse.setFsUpdateTime(DateUtils.formatDateToString(scmTbtemplet.getFsUpdateTime(), DateUtils.DATE_FORMAT));
            if (templetListResponse.getFiStatus() == Constants.FISTATUS_1) {
                templetListResponse.setFiStatusName(Constants.FISTATUS_1_VALUE);
            } else if (templetListResponse.getFiStatus() == Constants.FISTATUS_9) {
                templetListResponse.setFiStatusName(Constants.FISTATUS_9_VALUE);
            }
            templetListResponselist.add(templetListResponse);
        });
        return RestResponse.success(templetListResponselist, new PageInfo(list));
    }

    @Override
    @Transactional
    public RestResponse sava(TempletRequest templetRequest) {
        ScmTbtemplet scmTbtemplet = new ScmTbtemplet();
        String fsTempletId = "";
        try {
            // 拷贝字段
            BeanUtils.copyProperties(templetRequest, scmTbtemplet);

            // 获取自增流水号
            ScmTbseqno seqno = new ScmTbseqno();
            seqno.setFsCls("scm_tbtemplet");
            seqno.setFsShopGUID(templetRequest.getFsShopGUID());
            fsTempletId = tbSeqNoService.selectSeqNo(seqno);

            // 新增常用清单
            Date date = new Date();
            scmTbtemplet.setFsTempletId(fsTempletId);
            scmTbtemplet.setFsCreateTime(date);
            scmTbtemplet.setFsCreateUserId(scmTbtemplet.getFsUpdateUserId());
            scmTbtemplet.setFsCreateUserName(scmTbtemplet.getFsUpdateUserName());
            scmTbtemplet.setFsUpdateTime(date);
            scmTbtempletMapper.insertSelective(scmTbtemplet);

            logger.info("新增常用清单成功:fsShopGUID:{}, fsTempletId:{}", templetRequest.getFsShopGUID(), fsTempletId);
            // 获取新增常用清单明细
            List<TempletdtlEntity> templetdtlRequestList = templetRequest.getTempletdtlRequestList();
            if (templetdtlRequestList != null && templetdtlRequestList.size() > 0) {
                List<ScmTbtempletdtl> templetdtlList = new ArrayList<ScmTbtempletdtl>();
                short fiEntryNumber = 1;
                for (TempletdtlEntity templetdtlRequest : templetdtlRequestList) {
                    ScmTbtempletdtl scmTbtempletdtl = new ScmTbtempletdtl();
                    // 拷贝字段
                    BeanUtils.copyProperties(templetdtlRequest, scmTbtempletdtl);

                    scmTbtempletdtl.setFsTempletId(scmTbtemplet.getFsTempletId());
                    scmTbtempletdtl.setFsUpdateTime(date);
                    scmTbtempletdtl.setFsShopGUID(scmTbtemplet.getFsShopGUID());
                    scmTbtempletdtl.setFiEntryNumber(fiEntryNumber);
                    templetdtlList.add(scmTbtempletdtl);
                    fiEntryNumber++;
                }
                // 批量新增常用清单明细
                scmTbtempletdtlMapper.batchInsert(templetdtlList);
                logger.info("新增常用清单明细成功");
            }
        } catch (ServiceException e) {
            logger.info("fsShopGUID:{}, fsTempletId:{}, 新增常用清单失败:{}", templetRequest.getFsShopGUID(), fsTempletId, e.getMessage());
            throw ExceptionManager.fail("新增常用清单失败");
        }
        return RestResponse.success(null, "新增成功");
    }

    @Override
    @Transactional
    public RestResponse update(TempletRequest templetRequest) {
        String fsShopGUID = templetRequest.getFsShopGUID();
        String fsTempletId = templetRequest.getFsTempletId();
        try {
            // 查询常用清单
            ScmTbtemplet scmTbtemplet = new ScmTbtemplet();
            scmTbtemplet.setFsShopGUID(fsShopGUID);
            scmTbtemplet.setFsTempletId(fsTempletId);
            scmTbtemplet = scmTbtempletMapper.selectByPrimaryKey(scmTbtemplet);

            if (scmTbtemplet != null) {
                // 更新常用清单
                scmTbtemplet.setFiStatus(templetRequest.getFiStatus());
                scmTbtemplet.setFsApplyName(templetRequest.getFsApplyName());
                scmTbtemplet.setFsTempletName(templetRequest.getFsTempletName());
                scmTbtemplet.setFsNote(templetRequest.getFsNote());
                scmTbtemplet.setFsUpdateTime(new Date());
                scmTbtemplet.setFsUpdateUserId(templetRequest.getFsUpdateUserId());
                scmTbtemplet.setFsUpdateUserName(templetRequest.getFsUpdateUserName());
                scmTbtempletMapper.updateByPrimaryKey(scmTbtemplet);
                logger.info("更新常用清单成功:fsShopGUID:{}, fsTempletId:{}", fsShopGUID, fsTempletId);

                Date date = new Date();
                List<TempletdtlEntity> templetdtlRequestList = templetRequest.getTempletdtlRequestList();
                if (templetdtlRequestList != null && templetdtlRequestList.size() > 0) {
                    // 先删除后新增常用清单明细
                    scmTbtempletdtlMapper.deleteByFsTempletId(fsTempletId, fsShopGUID);

                    List<ScmTbtempletdtl> templetdtlList = new ArrayList<ScmTbtempletdtl>();
                    short fiEntryNumber = 1;
                    for (TempletdtlEntity templetdtlRequest : templetdtlRequestList) {
                        ScmTbtempletdtl scmTbtempletdtl = new ScmTbtempletdtl();
                        // 拷贝字段
                        BeanUtils.copyProperties(templetdtlRequest, scmTbtempletdtl);

                        scmTbtempletdtl.setFsTempletId(scmTbtemplet.getFsTempletId());
                        scmTbtempletdtl.setFsUpdateTime(date);
                        scmTbtempletdtl.setFsShopGUID(scmTbtemplet.getFsShopGUID());
                        scmTbtempletdtl.setFiEntryNumber(fiEntryNumber);
                        templetdtlList.add(scmTbtempletdtl);
                        fiEntryNumber++;
                    }
                    // 批量新增常用清单明细
                    scmTbtempletdtlMapper.batchInsert(templetdtlList);
                    logger.info("更新常用清单明细成功:fsShopGUID:{}, fsTempletId:{}", fsShopGUID, fsTempletId);
                }
            }

        } catch (Exception e) {
            logger.info("fsShopGUID:{}, fsTempletId:{}, 更新失败:{}", fsShopGUID, fsTempletId, e.getMessage());
            throw ExceptionManager.fail("更新失败");
        }
        return RestResponse.success(null, "编辑成功");
    }

    @Override
    @Transactional
    public RestResponse delete(TempletRequest templetRequest) {
        String fsShopGUID = templetRequest.getFsShopGUID();
        String fsTempletId = templetRequest.getFsTempletId();
        try {
            // 删除常用清单
            ScmTbtemplet scmTbtemplet = new ScmTbtemplet();
            scmTbtemplet.setFsShopGUID(fsShopGUID);
            scmTbtemplet.setFsTempletId(fsTempletId);
            scmTbtempletMapper.deleteByPrimaryKey(scmTbtemplet);

            logger.info("删除常用清单成功:fsShopGUID:{}, fsTempletId:{}", fsShopGUID, fsTempletId);
            // 删除常用清单明细
            scmTbtempletdtlMapper.deleteByFsTempletId(fsTempletId, fsShopGUID);
            logger.info("删除常用清单明细成功");

        } catch (Exception e) {
            logger.info("fsShopGUID:{}, fsTempletId:{}, 删除失败:{}", fsShopGUID, fsTempletId, e.getMessage());
            throw ExceptionManager.fail("删除失败");
        }
        return RestResponse.success(null, "删除成功");
    }

    @Override
    public RestResponse<TempletResponse> beforeEdit(TempletRequest templetRequest) {
        String fsTempletId = templetRequest.getFsTempletId();
        TempletResponse templetResponse = new TempletResponse();
        if (StringUtils.isNotBlank(fsTempletId)) {
            ScmTbtemplet scmTbtemplet = new ScmTbtemplet();
            scmTbtemplet.setFsShopGUID(templetRequest.getFsShopGUID());
            scmTbtemplet.setFsTempletId(fsTempletId);
            // 查询常用清单
            scmTbtemplet = scmTbtempletMapper.selectByPrimaryKey(scmTbtemplet);

            if (scmTbtemplet != null) {
                // 拷贝字段
                BeanUtils.copyProperties(scmTbtemplet, templetResponse);
                // 查询常用清单明细
                List<ScmTbtempletdtl> smTbtempletdtlList = scmTbtempletdtlMapper.selectByFsTempletId(scmTbtemplet.getFsTempletId(), scmTbtemplet.getFsShopGUID());
                if (smTbtempletdtlList != null && smTbtempletdtlList.size() > 0) {
                    List<TempletdtlEntity> templetdtlResponseList = new ArrayList<TempletdtlEntity>();
                    for (ScmTbtempletdtl scmTbtempletdtl : smTbtempletdtlList) {
                        TempletdtlEntity templetdtlResponse = new TempletdtlEntity();
                        // 拷贝字段
                        BeanUtils.copyProperties(scmTbtempletdtl, templetdtlResponse);
                        templetdtlResponseList.add(templetdtlResponse);
                    }
                    FinderList list = FinderList.build(TempletdtlEntity.class, this.getTempletdtlSchema(), templetdtlResponseList);
                    templetResponse.setTempletdtlList(list);
                }
            }
        } else {
            FinderList list = FinderList.build(TempletdtlEntity.class, this.getTempletdtlSchema(), new ArrayList<TempletdtlEntity>());
            BeanUtils.copyProperties(templetRequest, templetResponse);
        }
        return RestResponse.success(templetResponse);
    }

    private List getTempletdtlSchema() {
        List<ColTitle> list = new ArrayList<ColTitle>();
        list.add(new ColTitle("fsMaterialId", "物料代码", "left", 200));
        list.add(new ColTitle("fsMaterialName", "物料名称", "left", 100));
        list.add(new ColTitle("fsModelno", "规格", "center", 100));
        list.add(new ColTitle("fsOrderUnitName", "采购单位", "center", 100));
        list.add(new ColTitle("fdQty", "数量", "center", 100));
        list.add(new ColTitle("fsDtlNote", "明细备注", "center", 100));
        list.add(new ColTitle("__EDIT__", "操作", "center", 100, "fiEntryNumber"));
        return list;
    }

    @Override
    public RestResponse updateList(TempletRequest templetRequest) {
        try {
            JSONArray fsTempletIdArr = JSONObject.parseArray(templetRequest.getFsTempletId());
            List<ScmTbtemplet> scmTbtempletList = new ArrayList<ScmTbtemplet>();
            if (fsTempletIdArr.size() > 0) {
                for (int i = 0; i < fsTempletIdArr.size(); i++) {
                    if (fsTempletIdArr.get(i) != null) {
                        ScmTbtemplet scmTbtemplet = new ScmTbtemplet();
                        String fsTempletId = fsTempletIdArr.get(i).toString();
                        scmTbtemplet.setFsTempletId(fsTempletId);
                        scmTbtemplet.setFsShopGUID(templetRequest.getFsShopGUID());
                        scmTbtemplet.setFiSort(Short.parseShort((i + 1) + ""));
                        scmTbtemplet.setFsUpdateTime(new Date());
                        scmTbtemplet.setFsUpdateUserId(templetRequest.getFsUpdateUserId());
                        scmTbtemplet.setFsUpdateUserName(templetRequest.getFsUpdateUserName());
                        scmTbtempletList.add(scmTbtemplet);
                    }
                }
                if (scmTbtempletList.size() > 0) {
                    // 批量更新
                    scmTbtempletMapper.batchUpdate(scmTbtempletList);
                }
            }
        } catch (Exception e) {
            logger.info("fsShopGUID:{}, fsTempletIdList:{}, 保存失败:{}", templetRequest.getFsShopGUID(), templetRequest.getFsTempletId(), e.getMessage());
            throw ExceptionManager.fail("保存失败");
        }
        return RestResponse.success(null, "保存成功");
    }

    @Override
    public RestResponse importCheck(String fsTempletId, String templetdtls, String fsShopGUID) {
        // json字符串不为空时
        if (StringUtils.isNotBlank(templetdtls)) {
            TempleImportCheck templeImportCheck = new TempleImportCheck();
            List<TempletdtlEntity> templetdtlRequestesponseList = null;
            try {
                // 获取导入清单明细列表
                templetdtlRequestesponseList = JSONObject.parseArray(templetdtls, TempletdtlEntity.class);
            } catch (Exception e) {
                logger.info("fsShopGUID:{}, fsTempletIdList:{}, json转化失败:{}", fsShopGUID, fsTempletId, e.getMessage());
                return RestResponse.fail("json转化失败");
            }
            if (templetdtlRequestesponseList != null && templetdtlRequestesponseList.size() > 0) {
                // 查询店铺所有物料
                List<ScmTbmaterial> scmTbmaterialList = scmTbmaterialMapper.getAllMaterial(fsShopGUID, null, null);
                if (scmTbmaterialList != null && scmTbmaterialList.size() > 0) {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < templetdtlRequestesponseList.size(); i++) {
                        boolean flag = true;
                        String fsMaterialId = templetdtlRequestesponseList.get(i).getFsMaterialId();
                        BigDecimal fdQty = templetdtlRequestesponseList.get(i).getFdQty();
                        for (ScmTbmaterial scmTbmaterial : scmTbmaterialList) {
                            // 物料ID相同
                            if (StringUtils.equals(fsMaterialId, scmTbmaterial.getFsMaterialId())) {
                                flag = false;
                                break;
                            }
                        }
                        // 物料代码不正确
                        if (flag) {
                            sb.append("行号：" + (i + 1) + " 物料代码不正确 \r\n");
                        }
                        if (fdQty.compareTo(new BigDecimal(Constants.CONTANTS_STR_0)) <= 0) {
                            sb.append("行号：" + (i + 1) + " 数量不能小于等于零 \r\n");
                        }
                    }
                    // 导入物料有错误
                    if (sb.length() > 0) {
                        return RestResponse.fail(sb.toString());
                    }
                }

                // 获取常用清单明细列表
                List<ScmTbtempletdtl> scmTbtempletdtlList = scmTbtempletdtlMapper.selectByFsTempletId(fsTempletId, fsShopGUID);
                if (scmTbtempletdtlList != null && scmTbtempletdtlList.size() > 0) {
                    int add_num = 0;
                    int update_num = 0;
                    StringBuffer sb_all = new StringBuffer();
                    for (int i = 0; i < templetdtlRequestesponseList.size(); i++) {
                        boolean flag = true;
                        String fsMaterialId = templetdtlRequestesponseList.get(i).getFsMaterialId();
                        ScmTbtempletdtl scmTbtempletdtl_forEach = null;
                        StringBuffer sb = new StringBuffer();
                        for (ScmTbtempletdtl scmTbtempletdtl : scmTbtempletdtlList) {
                            // 物料ID相同
                            if (StringUtils.equals(fsMaterialId, scmTbtempletdtl.getFsMaterialId())) {
                                flag = false;
                                scmTbtempletdtl_forEach = scmTbtempletdtl;
                                break;
                            }
                        }
                        // 清单明细中不存在为新增
                        if (flag) {
                            add_num++;
                        } else {
                            if (!StringUtils.equals(templetdtlRequestesponseList.get(i).getFsMaterialName(), scmTbtempletdtl_forEach.getFsMaterialName())) {
                                sb.append("行号：" + (i + 1) + " 物料名称有差异");
                            }
                            if (!StringUtils.equals(templetdtlRequestesponseList.get(i).getFsModelno(), scmTbtempletdtl_forEach.getFsModelno())) {
                                if (sb.length() > 0) {
                                    sb.append("、规格有差异");
                                } else {
                                    sb.append("行号：" + (i + 1) + " 规格有差异");
                                }
                            }
                            String fsOrderUnitName = "";
                            // 基本单位和保存采购单位相同
                            if (StringUtils.equals(scmTbtempletdtl_forEach.getFsUnitIdSelected(), scmTbtempletdtl_forEach.getFsUnitId())) {
                                fsOrderUnitName = scmTbtempletdtl_forEach.getFsUnitName();
                            }

                            if (StringUtils.equals(scmTbtempletdtl_forEach.getFsUnitIdSelected(), scmTbtempletdtl_forEach.getFsOrderUnitId())) {
                                fsOrderUnitName = scmTbtempletdtl_forEach.getFsOrderUnitName();
                            }
                            // 采购单位和保存采购单位相同
                            if (!StringUtils.equals(templetdtlRequestesponseList.get(i).getFsOrderUnitName(), fsOrderUnitName)) {
                                if (sb.length() > 0) {
                                    sb.append("、采购单位有差异");
                                } else {
                                    sb.append("行号：" + (i + 1) + " 采购单位有差异");
                                }
                            }
                            if (sb.length() > 0) {
                                sb.append("\r\n");
                            }
                            sb_all.append(sb);
                            update_num++;
                        }
                    }
                    // 导入物料有差异
                    if (sb_all.length() > 0) {
                        templeImportCheck.setAdd(add_num);
                        templeImportCheck.setUpdate(update_num);
                        templeImportCheck.setRetMsg(sb_all.toString());
                        return RestResponse.success(templeImportCheck, "导入有差异");
                    } else {
                        templeImportCheck.setAdd(add_num);
                        templeImportCheck.setUpdate(update_num);
                        templeImportCheck.setRetMsg(sb_all.toString());
                        return RestResponse.success(templeImportCheck, "导入成功");
                    }
                }
            }
        }
        return RestResponse.success(null, "导入成功");
    }
}
